namespace EyeOpen.Warehouse.Mvc
{
	using System;
	using System.Collections.Generic;
	using System.Web.Mvc;
	using System.Web.Routing;
	using System.Web.SessionState;

	using EyeOpen.Warehouse.Mvc.ViewModel.Controllers;

	public class ControllerFactory : IControllerFactory
	{
		private readonly IDictionary<string, Type> controllerDictionary = 
			new Dictionary<string, Type>
				{
					{ GetControllerName<CustomerController>(), typeof(CustomerController) }
				};

		public IController CreateController(RequestContext requestContext, string controllerName)
		{
			if (!controllerDictionary.ContainsKey(controllerName))
			{
				return null;	
			}

			return 
				(IController)DependencyResolver.Current.GetService(controllerDictionary[controllerName]);
		}

		public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
		{
			return SessionStateBehavior.Default;
		}

		public void ReleaseController(IController controller)
		{
			var disposableController = controller as IDisposable;

			if (disposableController == null)
			{
				return;
			}

			disposableController.Dispose();
		}

		private static string GetControllerName<T>()
		{
			var controllerName = typeof(T).Name;

			return 
				controllerName
					.Substring(0, controllerName.IndexOf("Controller"));
		}
	}
}